//
//  MapClassViewController.m
//  WWXELuShang
//
//  Created by lanou on 15/12/17.
//  Copyright © 2015年 lanou. All rights reserved.
//

#import "MapClassViewController.h"
#import <CoreLocation/CoreLocation.h>
#import <MapKit/MapKit.h>
#import <MAMapKit/MAMapKit.h>
#import <AMapSearchKit/AMapSearchKit.h>
#import "MapTableViewCell.h"

@interface MapClassViewController ()<MAMapViewDelegate, AMapSearchDelegate,UITableViewDelegate, UITableViewDataSource>
@property (nonatomic, strong)MAMapView *mapView;

@property (nonatomic, strong)AMapSearchAPI *search;

@property (nonatomic, strong)MAPolyline *polyline;//路径渲染

@property (nonatomic, strong)UITableView *detailTableView;

@property (nonatomic, strong)NSMutableArray *detailArray;

@property (nonatomic, strong)NSMutableDictionary *detailDic;


@end

@implementation MapClassViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"smallArrow"] style:(UIBarButtonItemStylePlain) target:self action:@selector(getBack)];

    
    
    [self initMap];
    
    // Do any additional setup after loading the view.
}


- (UITableView *)detailTableView {
    if (!_detailTableView) {
        _detailTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, self.view.frame.size.height, kWidth, kHeight / 4) style:(UITableViewStylePlain)];
        _detailTableView.dataSource = self;
        _detailTableView.delegate = self;
        [_detailTableView registerClass:[MapTableViewCell class] forCellReuseIdentifier:@"cell"];
        [self.view addSubview:_detailTableView];
    }
    return _detailTableView;
}

- (NSMutableArray *)detailArray {
    if (!_detailArray) {
        _detailArray = [[NSMutableArray alloc]init];
    }
    return _detailArray;
}

- (NSMutableDictionary *)detailDic {
    if (!_detailDic) {
        _detailDic = [[NSMutableDictionary alloc]init];
    }
    
    return _detailDic;
}

//返回
- (void)getBack {
    
    [self.navigationController dismissViewControllerAnimated:YES completion:nil];
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
    NSLog(@"地图内存警告");
    [_mapView clearDisk];
    // Dispose of any resources that can be recreated.
}
#pragma mark -
#pragma mark ---地图方法---

//初始化地图
- (void)initMap {
    [MAMapServices sharedServices].apiKey = @"0e53ec5f2a187e9a7892f660a585c2a6";
    [AMapSearchServices sharedServices].apiKey = @"0e53ec5f2a187e9a7892f660a585c2a6";
    _mapView = [[MAMapView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    _mapView.delegate = self;
    _mapView.showsUserLocation = YES;//定位
    
    _mapView.showTraffic = self.switchTraffic;//路况开关
    
    [_mapView setUserTrackingMode:(MAUserTrackingModeFollow) animated:YES];//定位模式
    [_mapView setZoomLevel:13 animated:YES];//缩放比例
    
    [self.view addSubview:_mapView];
}

//定位改变方法
- (void)mapView:(MAMapView *)mapView didUpdateUserLocation:(MAUserLocation *)userLocation updatingLocation:(BOOL)updatingLocation {
    
    if (updatingLocation) {
        [_mapView setUserTrackingMode:(MAUserTrackingModeNone)];//定位模式
        //搜索模式
        
        if (_searchString != nil) {
            //假如需要搜索周边
            _search = [[AMapSearchAPI alloc] init];
            _search.delegate = self;
            //构造AMapPOIAroundSearchRequest对象,设置周边请求参数
            AMapPOIAroundSearchRequest *request = [[AMapPOIAroundSearchRequest alloc] init];
            //位置为当前的坐标周围
            request.location = [AMapGeoPoint locationWithLatitude:userLocation.coordinate.latitude longitude:userLocation.coordinate.longitude];
            
            request.keywords = self.searchString;
            request.radius = 25000;
            request.sortrule = 0;
            request.requireExtension = YES;
            
            //发起周边搜索
            [_search AMapPOIAroundSearch:request];
            
        }
    }
}


//实现POI搜索对应的回调函数
- (void)onPOISearchDone:(AMapPOISearchBaseRequest *)request response:(AMapPOISearchResponse *)response {
    if (response.pois.count == 0) {
        return;
    }
    
    if (_detailDic) {
        [self.detailDic removeAllObjects];
        self.detailDic = nil;
    }
    
    for (AMapPOI *p in response.pois) {
        //添加大头针
        MAPointAnnotation *annotation = [[MAPointAnnotation alloc] init];
        annotation.coordinate = CLLocationCoordinate2DMake(p.location.latitude, p.location.longitude);
        annotation.title = p.name;
        annotation.subtitle = p.address;
        
        [self.detailDic setValue:p forKey:p.name];
        
        [_mapView addAnnotation:annotation];
    }
}
//设置大头针的View
- (MAAnnotationView *)mapView:(MAMapView *)mapView viewForAnnotation:(id<MAAnnotation>)annotation {
    if ([annotation isKindOfClass:[MAPointAnnotation class]]) {
        static NSString *pointReuseIndetifier = @"pointReuseIndetifier";//标记值
        MAAnnotationView *pointView = [_mapView dequeueReusableAnnotationViewWithIdentifier:pointReuseIndetifier];//重用队列获取
        if (pointView == nil) {
            //如果为空 创建
            pointView = [[MAAnnotationView alloc]initWithAnnotation:annotation reuseIdentifier:pointReuseIndetifier];
        }
        pointView.canShowCallout = YES; //设置气泡可以弹出
        pointView.image = [UIImage imageNamed:@"flag0002"];
        //给大头针添加一个导航按钮
        UIButton *button = [UIButton buttonWithType:(UIButtonTypeSystem)];
        button.frame = CGRectMake(0, 0, 30, 20);
        [button setTitle:@"路线" forState:(UIControlStateNormal)];
        [button addTarget:self action:@selector(changeDriving:) forControlEvents:(UIControlEventTouchUpInside)];
        pointView.rightCalloutAccessoryView = button;
        return pointView;
    }
    return nil;
}

//选中的大头针调用此方法
- (void)mapView:(MAMapView *)mapView didSelectAnnotationView:(MAAnnotationView *)view {
    
    
    [_mapView setCenterCoordinate:view.annotation.coordinate animated:YES];
    [UIView animateWithDuration:0.5 animations:^{
        view.image = [UIImage imageNamed:@"flag0001"];
    }];
    
    
    if (_detailArray) {
        [self.detailArray removeAllObjects];
        self.detailArray = nil;
    }
    
    AMapPOI *poi = self.detailDic[view.annotation.title];
    [self.detailArray addObject:poi.name];
    [self.detailArray addObject:poi.address];
    
    NSString *tel = [poi.tel componentsSeparatedByString:@";"][0];//电话 取封号前面的;
    [self.detailArray addObject:tel];
    
    [self.detailTableView reloadData];
    [self hiddenTableView];
}



//取消选中大头针调用的方法
- (void)mapView:(MAMapView *)mapView didDeselectAnnotationView:(MAAnnotationView *)view {
    
    view.image = [UIImage imageNamed:@"flag0002"];
    
    [self hiddenTableView];
    
}



#pragma mark -
#pragma mark ---导航数据---
//导航方法
- (void)changeDriving:(UIButton *)button {
    //获取当前大头针
    MAPointAnnotation *annotation = [_mapView selectedAnnotations][0];
    //初始化路径
    AMapDrivingRouteSearchRequest *request = [[AMapDrivingRouteSearchRequest alloc] init];
    //路径起点
    request.origin = [AMapGeoPoint locationWithLatitude:_mapView.userLocation.location.coordinate.latitude longitude:_mapView.userLocation.location.coordinate.longitude];
    //路径终点
    request.destination = [AMapGeoPoint locationWithLatitude:annotation.coordinate.latitude longitude:annotation.coordinate.longitude];
    request.strategy = 2;//距离优先
    request.requireExtension = YES;
    //发起路径搜索
    [_search AMapDrivingRouteSearch:request];
}

//实现路径搜索回调函数

- (void)onRouteSearchDone:(AMapRouteSearchBaseRequest *)request response:(AMapRouteSearchResponse *)response {
    if (response.route == nil) {
        return;
    }
    if (_polyline) {
        [_mapView removeOverlay:_polyline];
        _polyline = nil;
    }
    //通过AMapNavigationSearchResponse对象处理搜索结果
    AMapPath *mapPath = response.route.paths[0];
    NSMutableArray *latitudeArray = [NSMutableArray array];
    NSMutableArray *longitudeArray = [NSMutableArray array];
    for (AMapStep *mapStep in mapPath.steps) {
        NSArray *arr = [mapStep.polyline componentsSeparatedByString:@";"];
        for (NSString *str in arr) {
            NSArray *arr2 = [str componentsSeparatedByString:@","];
            [latitudeArray addObject:arr2[1]];
            [longitudeArray addObject:arr2[0]];
        }
    }
    NSInteger count = latitudeArray.count;
    CLLocationCoordinate2D coordinates[count];
    for (int i = 0; i < count; i ++) {
        coordinates[i] = CLLocationCoordinate2DMake([latitudeArray[i] doubleValue], [longitudeArray[i] doubleValue]);
    }
    _polyline = [MAPolyline polylineWithCoordinates:coordinates count:count];
    [_mapView addOverlay:_polyline];
}

//地图渲染方法
- (MAOverlayRenderer *)mapView:(MAMapView *)mapView rendererForOverlay:(id<MAOverlay>)overlay {
    if ([overlay isKindOfClass:[MAPolyline class]]) {
        MAPolylineRenderer *renderer = [[MAPolylineRenderer alloc]initWithOverlay:(MAPolyline *)overlay];
        renderer.strokeColor = [UIColor greenColor];
        renderer.lineWidth = 5;
        return renderer;
    }
    return nil;
}


#pragma mark -
#pragma mark ---tableView代理---

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return 3;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSArray *iconArray = @[@"map_marker", @"telephone"];
    
    MapTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    cell.deTailLabel.text = self.detailArray[indexPath.row];
    
    if ([self.detailArray[indexPath.row] isEqualToString:@""]) {
        cell.deTailLabel.text = @"暂无数据";
    }
    
    if (indexPath.row == 0) {
        cell.userInteractionEnabled = NO;
        cell.deTailLabel.font = [UIFont boldSystemFontOfSize:18];
    }else {
        cell.iconView.image = [UIImage imageNamed:iconArray[indexPath.row - 1]];
        cell.iconView.frame = CGRectMake(cell.iconView.frame.origin.x, cell.frame.size.height / 4, cell.frame.size.height / 2, cell.frame.size.height / 2);
    }
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return kHeight / 12;
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.row == 1) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"是否导航" message:nil preferredStyle:(UIAlertControllerStyleActionSheet)];
        UIAlertAction * cancelAction = [UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleCancel) handler:nil];
        UIAlertAction *openMapAction = [UIAlertAction actionWithTitle:@"开始导航" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
            [self openSystemMap];
        }];
        [alert addAction:cancelAction];
        [alert addAction:openMapAction];
        [self presentViewController:alert animated:YES completion:nil];
    }
    if (indexPath.row == 2) {
        
        if ([self.detailArray[indexPath.row] isEqualToString:@""]) {
            return;
        }
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:self.detailArray[indexPath.row] preferredStyle:(UIAlertControllerStyleAlert)];
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleCancel) handler:nil];
        UIAlertAction *callAction = [UIAlertAction actionWithTitle:@"呼叫" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
            [self callPerson];
        }];
        [alert addAction:cancelAction];
        [alert addAction:callAction];
        [self presentViewController:alert animated:YES completion:nil];
    }
}

- (void)callPerson {
    //呼叫
    NSString *telSting = [@"tel://" stringByAppendingString:self.detailArray[2]];
    [[UIApplication sharedApplication]openURL:[NSURL URLWithString:telSting]];
}

- (void)openSystemMap {
    //跳转系统地图
    MAPointAnnotation *annotation =  self.mapView.selectedAnnotations[0];
    MKMapItem *currentLocation = [[MKMapItem alloc] initWithPlacemark:[[MKPlacemark alloc]initWithCoordinate: self.mapView.userLocation.location.coordinate addressDictionary:nil]] ;
    MKMapItem *toLocation = [[MKMapItem alloc] initWithPlacemark:[[MKPlacemark alloc] initWithCoordinate:annotation.coordinate addressDictionary:nil]];
    [MKMapItem openMapsWithItems:@[currentLocation, toLocation]
                   launchOptions:@{MKLaunchOptionsDirectionsModeKey: MKLaunchOptionsDirectionsModeDriving,
                                   MKLaunchOptionsShowsTrafficKey: [NSNumber numberWithBool:YES]}];
}



//tableView推出动画

- (void)hiddenTableView {
    
    CGFloat height;
    if (self.detailTableView.frame.origin.y == self.view.frame.size.height) {
        height = -kHeight / 4;
    }else {
        height = kHeight / 4;
    }
    
    [UIView animateWithDuration:0.5 animations:^{
        
        self.detailTableView.transform = CGAffineTransformTranslate(self.detailTableView.transform, 0, height);
        
    }];
    
}
/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
